#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <string.h>

#define RES_200 "200 OK"
#define RES_404 "404 Not Found"
#define RES_501 "501 Not Implemented"

int main(int argc, char **argv)
{
	int fd;
	int n;
    long len;
	char buff[1024];
    struct stat st;

	if (argc == 1) {
		n = snprintf(buff, sizeof(buff), "Wrong way to run\n");
		goto __error;
	}
	else if ((fd = open(argv[1], O_RDONLY)) < 0) {
		n = snprintf(buff, sizeof(buff), "HTTP/1.1 %s\r\n", RES_404);
		n += snprintf(buff+n, sizeof(buff)-n, "Content-Length: %d\r\n\r\n", (int)strlen(RES_404));
		n += snprintf(buff+n, sizeof(buff)-n, "%s", RES_404);
		goto __error;
	}

    if (fstat(fd, &st) < 0) {
		n = snprintf(buff, sizeof(buff), "HTTP/1.1 %s\r\n", RES_501);
		n += snprintf(buff+n, sizeof(buff)-n, "Content-Length: %d\r\n\r\n", (int)strlen(RES_501));
		n += snprintf(buff+n, sizeof(buff)-n, "%s", RES_501);
        goto __error;
    }
    len = st.st_size;

    n = snprintf(buff, sizeof(buff), "HTTP/1.1 200 OK\r\n");
    n+= snprintf(buff+n, sizeof(buff)-n, "Content-Length: %ld\r\n\r\n", len);
    if (write(1, buff, n) != n)
        exit(0);

	while ((n = read(fd, buff, sizeof(buff))) > 0)
		write(1, buff, n);
	exit(0);

__error:
	write(1, buff, n);
	exit(1);
}

